import logging
import sys

import allure
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.chrome.options import Options

rootdir = sys.path[0]
# from testcases.conftest import add_step_wapper
# 定义一个装饰器，实现添加步骤功能
def add_step_wapper(func):
    def wrapper(*args, **kwargs):
        with allure.step(args[1]):
            im_func = func(*args, **kwargs)
        return im_func

    return wrapper


class Base:
    # 起始页面，
    _base_url = "https://work.weixin.qq.com/wework_admin/loginpage_wx"

    def __init__(self, base_driver: WebDriver = None):
        # 如果base_driver为空，表示还没有进行driver的初始化，则初始化driver
        # 如果base_driver不为空，表示是从其他的页面跳过转来的，不用初始化driver的
        if base_driver is None:
            chrome_options = Options()
            chrome_options.add_argument('–no-sandbox')
            chrome_options.add_argument("–disable-dev-shm-usage")
            chrome_options.add_argument('-headless')
            self.driver = webdriver.Chrome(options=chrome_options,executable_path="/usr/local/driver/chromedriver")
            self.driver.get(self._base_url)
        else:
            self.driver = base_driver
        self.driver.maximize_window()
        self.driver.implicitly_wait(5)

    def find(self, by, locator=None):
        """
        by:定位方式
        locator：定位元素
        封装find方法，比如在每次查找后添加日志等
        :return:
        """
        # 有可能传入的参数是个元祖(定位方式，定位元素)
        # 还有可能传入的两个参数by，locator
        if locator is None:
            logging.info(f"定位到元素{by}")
            return self.driver.find_element(*by)
        else:
            logging.info(f"定位到元素{by, locator}")
            return self.driver.find_element(by=by, value=locator)

    @add_step_wapper
    def find_and_add_step(self, step_tile, by, locator=None):
        return self.find(by, locator=None)

    def find_wait(self, by, locator=None):
        """
        封装显示等待，
        :param by:
        :param locator:
        :return: 定位到返回True，没有定位到返回False
        """

        def wait(x):
            """
            添加等待方法，获取完成登录后首页到logo，
            :param x: 无实际意义
            :return: 元素
            表示如果返回元素不为空，表示已经进入首页，如果为空表示还未登录首页
            """
            return self.find(by, locator)

        try:
            WebDriverWait(self.driver, 30).until(wait)
            return self.find(by, locator)
        except TimeoutException:
            print("未定位到元素")
            return

    #
    def save_png(self, filename,name=None):
        """
        :param filename: 图片路径
        :param name: 添加到报告中到图片名称
        :return:
        """
        self.driver.save_screenshot(f"{rootdir}/screenshot/{filename}.png")
        allure.attach.file(f"{rootdir}/screenshot/{filename}.png", name=name,attachment_type=allure.attachment_type.PNG)

